<!DOCTYPE html>
<head>
    <title>视频监控</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name=”viewport” content=”width=device-width, initial-scale=1″/>
</head>
<script src="/static/jquery.min.js" type="text/javascript"></script>
<script src="/static/mpegts.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="/static/jquery-ui.min.css"/>
<script type="text/javascript" src="/static/jquery-ui.min.js"></script>
<style>

    video::-webkit-media-controls-fullscreen-button {
        display: none;
    }

    video::-webkit-media-controls-play-button {
        display: none;
    }

    video::-webkit-media-controls-mute-button {
        display: none;
    }

    video::-webkit-media-controls-toggle-closed-captions-button {
        display: none;
    }


    .my-play {
        background-image: url("/static/images/PhPlayFill.png");
        background-size: 100% 100%;
        width: 20px;
        height: 20px;
    }

    .my-play-stop {
        background-image: url("/static/images/TablerPlayerStopFilled.png");
        background-size: 100% 100%;
        width: 20px;
        height: 20px;
    }

    .my-screen {
        background-image: url("/static/images/MapFullscreen.png");
        background-size: 100% 100%;
        margin-left: 20px;
        width: 20px;
        height: 20px;
    }

    .volume-player {

        width: 50%;
        height: 10px;
        margin-left: 20px;
        background: orangered;

    }

    video {
        object-fit: fill;
    }

</style>
<body style="margin: 0!important;width: 100%;height: 98vh;overflow: auto">
<div style="padding: 10px 0;height: 2%;width: 100%;background: #E8EAED;">
    <button onclick="playAll()" style="background: #E6A23C;color: #fff;border: 1px solid #E6A23C;cursor: pointer;">全部播放</button>
    <button onclick="stopAll()" style="margin-left: 10px;background: #E6A23C;color: #fff;border: 1px solid #E6A23C;cursor: pointer;">全部关闭</button>
    <button onclick="ssdj()" style="margin-left: 10px;background: #E6A23C;color: #fff;border: 1px solid #E6A23C;cursor: pointer;">实时对讲</button>
    <select id="bitstream" name="bitstream" style="margin-left: 10px">
        <option value="1">流畅（子码流）</option>
        <option value="0">清晰（主码流）</option>
    </select>
    <select id="buju" name="buju" onchange="handleChange()" style="margin-left: 10px">
        <option value="1.2">1行×2列</option>
        <option value="1.1">1行×1列</option>
        <option value="2.2">2行×2列</option>
        <option value="3.3">3行×3列</option>
        <option value="4.4">4行×4列</option>
        <option value="5.5">5行×5列</option>
    </select>

</div>

<div id="content-body" style="width: 100%;height: 97%;display: flex;flex-wrap: wrap">

</div>

<!--<div id="xxoo" style="background-color: #333333;border-radius: 10px; overflow: hidden; width: 800px; height: 600px;">


</div>-->

<script type="text/javascript">

    var globalPlayMap = new Map()
    var TNO;
    var globalbitstream = 1


    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg); //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    function ssdj(){
        alert('功能暂未开放')
    }

    function playAll() {
        var obj = document.getElementById('buju'); // 定位id
        var index = obj.selectedIndex; // 选中索引
        var value = obj.options[index].value;
        var zuobiao = value.split('.')
        var rows = parseInt(zuobiao[0])
        var cols = parseInt(zuobiao[1])
        const arr = [];

        for (var i = 1; i < rows * cols + 1; i++) {
            arr.push(i)
        }


        const result = arr.flatMap((value, index, array) => {
            if (index % rows === 0) {
                return [array.slice(index, index + rows)];
            }
            return [];
        });

        for (let i = 0; i < rows; i++) {

            for (let j = 0; j < cols; j++) {
                $('#v-play-' + TNO + '-' + result[i][j]).click()
            }
        }


    }

    function stopAll() {
        var obj = document.getElementById('buju'); // 定位id
        var index = obj.selectedIndex; // 选中索引
        var value = obj.options[index].value;
        var zuobiao = value.split('.')
        var rows = parseInt(zuobiao[0])
        var cols = parseInt(zuobiao[1])


        for (var i = 1; i < rows * cols + 1; i++) {
            $.ajax({
                url: 'http://10.144.25.100:13000/api/video/stop',
                type: 'GET',
                data: {tag: TNO + '-' + i, bitstream: globalbitstream},
                success: function (res) {
                    console.log(res)
                },
                error: function (err) {

                }
            })
        }


    }

    window.onload = function () {
        TNO = getUrlParam("tno")
        handleChange()
        playAll()
    }

    function bindSjVideo(id) {
        var video = document.getElementById('v-' + id)
        var frame = document.getElementById('v-f-' + id)

        video.addEventListener('loadeddata', function () {
            console.log(video.duration + " " + video.currentTime)
            const frameRate = Math.round(video.duration / video.currentTime)
            frame.textContent = '速率：' + frameRate
        });

    }

    function bindSjPlay(id) {
        var frame = document.getElementById('v-f-' + id)
        var videoElement = document.getElementById('v-' + id)

        $('#v-play-' + id).click(() => {
            var cl = $("#v-play-" + id).attr("class");
            if (cl == 'my-play') {

                if (!globalPlayMap.has(id)) {

                    $.ajax({
                        url: 'http://10.144.25.100:13000/api/video/play',
                        type: 'GET',
                        data: {tag: id, bitstream: globalbitstream},
                        success: function (response) {
                            // 处理服务器响应
                            if (response.code === 200) {

                                var socket = new WebSocket("ws://10.144.25.100:3333/websocket/video/status/" + id);

                                socket.onopen = function (event) {
                                    console.log("WebSocket opened: " + event);
                                };

                                socket.onmessage = function (event) {
                                    if (event.data !== "心跳") {
                                        var json = JSON.parse(event.data);
                                        if (json.status === 'stop') {
                                            var p = globalPlayMap.get(id)
                                            p.destroy()
                                            p = null;
                                            globalPlayMap.delete(id)
                                            $("#v-play-" + id).prop("class", "my-play");
                                            frame.textContent = '速率：0KB/S'
                                        }

                                    } else {
                                        if (!globalPlayMap.has(id)) {
                                            let config = {
                                                liveBufferLatencyChasing: true,
                                                //liveBufferLatencyMaxLatency: 5,
                                                //liveBufferLatencyMinRemain: 1,
                                                enableStashBuffer: true,
                                                enableWorker: true,
                                                stashInitialSize: 64,
                                                isLive: true,
                                                liveBufferLatencyChasingOnPaused: true,
                                                liveSync: true,
                                                //liveSyncMaxLatency: 2,
                                                //liveSyncTargetLatency: 1,
                                                //lazyLoadMaxDuration: 10,
                                                //lazyLoadRecoverDuration: 10,
                                                autoCleanupSourceBuffer: true,
                                                //autoCleanupMaxBackwardDuration: 10,
                                                //autoCleanupMinBackwardDuration: 5,
                                            };
                                            var player = mpegts.createPlayer(
                                                {
                                                    type: 'mse', // mse,flv
                                                    isLive: true,
                                                    url: 'ws://10.144.25.100:3333/websocket/video/flv/' + id,
                                                    hasAudio: true,
                                                    hasVideo: true,
                                                    enableStashBuffer: true
                                                },
                                                config,
                                            );


                                            player.attachMediaElement(videoElement);
                                            player.load();
                                            player.play();

                                            player.on(mpegts.Events.STATISTICS_INFO, (statisticsInfo) => {
                                                frame.textContent = '速率：' + statisticsInfo.speed.toFixed(2) + 'KB/S'
                                            });
                                            globalPlayMap.set(id, player)


                                        }


                                    }
                                };

                                socket.onclose = function (event) {
                                    console.log("WebSocket closed: " + event);
                                };
                            }
                        },
                        error: function (err) {
                            console.log(err)
                        }
                    });


                } else {
                    var player = globalPlayMap.get(id)
                    // player.load();
                    player.play()
                }

                $("#v-play-" + id).prop("class", "my-play-stop");
            } else if (cl === 'my-play-stop') {

                var player = globalPlayMap.get(id)
                player.pause()
                $("#v-play-" + id).prop("class", "my-play");


            }
        })
    }

    function bindSjVol(id) {
        $('#v-vol-' + id).slider({
            range: "min",
            min: 0,
            max: 100,
            value: 50,
            slide: function (event, ui) {
                // 滑动触发
                var player = globalPlayMap.get(id);
                player.volume = ui.value / 100
            },
            change: function (event, ui) {
                // change事件
            }
        });
    }

    function bindQp(id) {
        $('#v-s-' + id).click(() => {
            var ele = document.getElementById('v-' + id);
            if (ele.requestFullscreen) {
                ele.requestFullscreen();
            } else if (ele.mozRequestFullScreen) {
                ele.mozRequestFullScreen();
            } else if (ele.webkitRequestFullScreen) {
                ele.webkitRequestFullScreen();
            }
        })


    }

    function handleChange() {
        var obj = document.getElementById('buju'); // 定位id
        var index = obj.selectedIndex; // 选中索引
        var value = obj.options[index].value; // 选中值
        for (let [key, player] of globalPlayMap) {
            player.destroy()
            player = null;
        }

        globalPlayMap.clear()


        if (value == '1.1') {

            $('#content-body').html('');

            var dom = document.createElement("div")
            dom.id = 'div-' + TNO + '-1'
            dom.style.height = '100%'
            dom.style.width = '100%'
            dom.style.border = '1px solid #333'
            // dom.style.backgroundColor = '#097AAE'

            var video = document.createElement('video')
            video.id = 'v-' + TNO + '-1'
            video.autoplay = true;
            video.controls = true;
            video.muted = false;
            video.style.width = '100%';
            video.style.height = '90%';
            dom.append(video)

            var controlDiv = document.createElement('div')
            controlDiv.id = 'control-' + TNO + '-1'
            controlDiv.style.height = '10%'
            controlDiv.style.width = '100%'
            controlDiv.style.backgroundColor = '#000'
            controlDiv.style.marginTop = '-4px'
            controlDiv.style.display = 'flex'
            controlDiv.style.justifyContent = 'space-between'

            var left = document.createElement('div')
            left.style.height = '100%'
            left.style.width = '60%'
            left.style.display="flex"
            left.style.alignItems="center"
            var span = document.createElement('span')
            span.style.color = '#fff'
            span.style.fontSize='12px'
            span.innerHTML = "通道" + 1
            left.append(span)

            var slspan = document.createElement('span')
            slspan.id = 'v-f-' + TNO + '-1'
            slspan.style.color = '#fff'
            slspan.style.fontSize='12px'
            slspan.innerHTML = "速率：0KB/S"
            slspan.style.marginLeft = '10px'
            left.append(slspan)


            controlDiv.append(left)
            var right = document.createElement('div')
            right.style.height = '100%'
            right.style.width = '35%'
            right.style.display = 'flex'
            right.style.alignItems = 'center'

            var playBtn = document.createElement('span')
            playBtn.id = 'v-play-' + TNO + '-1'
            playBtn.className = 'my-play'

            right.append(playBtn)

            var volumn = document.createElement('div')
            volumn.id = 'v-vol-' + TNO + '-1'
            volumn.className = 'volume-player'
            right.append(volumn)


            var screen = document.createElement('span')
            screen.id = 'v-s-' + TNO + '-1'
            screen.className = 'my-screen'
            right.append(screen)


            controlDiv.append(right)

            dom.append(controlDiv)


            $('#content-body').append(dom)

            bindSjVideo(TNO + '-1')
            bindSjPlay(TNO + '-1')
            bindSjVol(TNO + '-1')
            bindQp(TNO + '-1')

        } else if (value == '1.2') {
            $('#content-body').html('');
            for (var i = 1; i <= 2; i++) {

                var dom = document.createElement("div")
                dom.id = 'div-' + TNO + '-' + i
                dom.style.height = '100%'
                dom.style.width = 'calc(50% - 5px)'
                dom.style.border = '1px solid #333'
                // dom.style.backgroundColor = '#097AAE'

                var video = document.createElement('video')
                video.id = 'v-' + TNO + '-' + i
                video.autoplay = true;
                video.controls = true;
                video.muted = false;
                video.style.width = '100%';
                video.style.height = '90%';
                dom.append(video)

                var controlDiv = document.createElement('div')
                controlDiv.id = 'control-' + TNO + '-' + i
                controlDiv.style.height = '10%'
                controlDiv.style.width = '100%'
                controlDiv.style.backgroundColor = '#000'
                controlDiv.style.marginTop = '-4px'
                controlDiv.style.display = 'flex'
                controlDiv.style.justifyContent = 'space-between'

                var left = document.createElement('div')
                left.style.height = '100%'
                left.style.width = '60%'
                left.style.display="flex"
                left.style.alignItems="center"
                var span = document.createElement('span')
                span.style.color = '#fff'
                span.style.fontSize = '12px'
                span.innerHTML = "通道" + i
                left.append(span)

                var slspan = document.createElement('span')
                slspan.id = 'v-f-' + TNO + '-' + i
                slspan.style.color = '#fff'
                slspan.style.fontSize = '12px'
                slspan.innerHTML = "速率：0KB/S"
                slspan.style.marginLeft = '10px'
                left.append(slspan)


                controlDiv.append(left)
                var right = document.createElement('div')
                right.style.height = '100%'
                right.style.width = '35%'
                right.style.display = 'flex'
                right.style.alignItems = 'center'

                var playBtn = document.createElement('span')
                playBtn.id = 'v-play-' + TNO + '-' + i
                playBtn.className = 'my-play'

                right.append(playBtn)

                var volumn = document.createElement('div')
                volumn.id = 'v-vol-' + TNO + '-' + i
                volumn.className = 'volume-player'
                right.append(volumn)


                var screen = document.createElement('span')
                screen.id = 'v-s-' + TNO + '-' + i
                screen.className = 'my-screen'
                right.append(screen)


                controlDiv.append(right)

                dom.append(controlDiv)

                $('#content-body').append(dom)
            }
            bindSjVideo(TNO + '-1')
            bindSjPlay(TNO + '-1')
            bindSjVol(TNO + '-1')
            bindQp(TNO + '-1')

            bindSjVideo(TNO + '-2')
            bindSjPlay(TNO + '-2')
            bindSjVol(TNO + '-2')
            bindQp(TNO + '-2')


        } else {
            $('#content-body').html('');
            var zuobiao = value.split('.')
            var rows = parseInt(zuobiao[0])
            var cols = parseInt(zuobiao[1])
            const arr = [];

            for (var i = 1; i < rows * cols + 1; i++) {
                arr.push(i)
            }


            const result = arr.flatMap((value, index, array) => {
                if (index % rows === 0) {
                    return [array.slice(index, index + rows)];
                }
                return [];
            });

            for (let i = 0; i < rows; i++) {

                for (let j = 0; j < cols; j++) {

                    var dom = document.createElement("div")
                    dom.id = 'div-' + TNO + '-' + result[i][j]
                    dom.style.height = (100 / cols).toFixed(2) + '%'
                    dom.style.width = 'calc(calc(100% / ' + rows + ') - 5px)'
                    dom.style.border = '1px solid #333'
                    // dom.style.backgroundColor = '#097AAE'

                    var video = document.createElement('video')
                    video.id = 'v-' + TNO + '-' + result[i][j]
                    video.autoplay = true;
                    video.controls = true;
                    video.muted = false;
                    video.style.width = '100%';
                    video.style.height = '90%';
                    dom.append(video)

                    var controlDiv = document.createElement('div')
                    controlDiv.id = 'control-' + TNO + '-' + result[i][j]
                    controlDiv.style.height = '10%'
                    controlDiv.style.width = '100%'
                    controlDiv.style.backgroundColor = '#000'
                    controlDiv.style.marginTop = '-4px'
                    controlDiv.style.display = 'flex'
                    controlDiv.style.justifyContent = 'space-between'

                    var left = document.createElement('div')
                    left.style.height = '100%'
                    left.style.width = '60%'
                    left.style.display="flex"
                    left.style.alignItems="center"
                    var span = document.createElement('span')
                    span.style.color = '#fff'
                    span.style.fontSize = '12px'
                    span.innerHTML = "通道" + result[i][j]
                    left.append(span)

                    var slspan = document.createElement('span')
                    slspan.id = 'v-f-' + TNO + '-' + result[i][j]
                    slspan.style.color = '#fff'
                    slspan.style.fontSize = '12px'
                    slspan.innerHTML = "速率：0KB/S"
                    slspan.style.marginLeft = '10px'
                    left.append(slspan)


                    controlDiv.append(left)
                    var right = document.createElement('div')
                    right.style.height = '100%'
                    right.style.width = '35%'
                    right.style.display = 'flex'
                    right.style.alignItems = 'center'

                    var playBtn = document.createElement('span')
                    playBtn.id = 'v-play-' + TNO + '-' + result[i][j]
                    playBtn.className = 'my-play'

                    right.append(playBtn)

                    var volumn = document.createElement('div')
                    volumn.id = 'v-vol-' + TNO + '-' + result[i][j]
                    volumn.className = 'volume-player'
                    right.append(volumn)


                    var screen = document.createElement('span')
                    screen.id = 'v-s-' + TNO + '-' + result[i][j]
                    screen.className = 'my-screen'
                    right.append(screen)


                    controlDiv.append(right)

                    dom.append(controlDiv)

                    $('#content-body').append(dom)

                    bindSjVideo(TNO + '-' + result[i][j])
                    bindSjPlay(TNO + '-' + result[i][j])
                    bindSjVol(TNO + '-' + result[i][j])
                    bindQp(TNO + '-' + result[i][j])


                }


            }


        }
    }
</script>

</body>
</html>
